/*
 * @ProjectName: flutter_common
 * @Package: 
 * @ClassName: register.dart
 * @Description: 注册页面
 * @User: Page.Su
 * @Date: 2020/8/24
 * @Time: 18:01
 * @UpdateDate: 2020/8/24 18:01
 */

import 'dart:async';

import 'package:fdottedline/fdottedline.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_su/common/app_color.dart';
import 'package:flutter_su/common/fun.dart';
import 'package:flutter_su/common/input_check.dart';
import 'package:flutter_su/common/language_text.dart';
import 'package:flutter_su/common/show.dart';
import 'package:flutter_su/enum/language_type.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  // 显示输入框底部虚线
  StreamController<bool> _hiddenTextFileLineByEmail = StreamController();
  StreamController<bool> _hiddenTextFileLineByPassword = StreamController();
  StreamController<bool> _hiddenTextFileLineBySecondPassword =
      StreamController();

  // 输入框控制器
  TextEditingController _passwordInputController = TextEditingController();
  TextEditingController _secondPasswordInputController =
      TextEditingController();
  TextEditingController _emailInputController = TextEditingController();

  // 控制注册按钮刷新
  StreamController<String> _disableShowController =
      StreamController.broadcast();

  // 控制错误显示
  StreamController<String> _showErrorMessageController = StreamController();

  @override
  void dispose() {
    _hiddenTextFileLineByEmail.close();
    _hiddenTextFileLineByPassword.close();
    _hiddenTextFileLineBySecondPassword.close();

    _passwordInputController.dispose();
    _secondPasswordInputController.dispose();
    _emailInputController.dispose();

    _disableShowController.close();

    _showErrorMessageController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: LanguageText.registerText,
        centerTitle: true,
        elevation: 0,
        backgroundColor: AppColor.MAIN_COLOR_BLUE,
      ),
      backgroundColor: AppColor.MAIN_COLOR_BLUE,
      body: _body(),
    );
  }

  Widget _body() {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: SingleChildScrollView(
        child: Container(
          color: AppColor.TRANSPARENT,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _input(),
              _registerButton(),
            ],
          ),
        ),
      ),
    );
  }

  // 所有输入输入框
  Widget _input() {
    return Container(
      margin: EdgeInsets.only(
        left: SFunCommon.width(36),
        right: SFunCommon.width(36),
      ),
      padding: EdgeInsets.only(
        top: SFunCommon.height(250),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _inputEmail(),
          _inputPassword(),
          _inputSecondPassword(),
//          _registerTipText(),  // 暂时修改为弹窗式
        ],
      ),
    );
  }

  // 校验不通过的提示
  Widget _registerTipText() {
    return StreamBuilder(
      initialData: '',
      stream: _showErrorMessageController.stream,
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        return Offstage(
          offstage: snapshot.data.isEmpty,
          child: SFunCommon.text(
            SFunCommon.fontStyle(
              AppColor.MAIN_COLOR_CYAN,
              fontSize: 30,
            ),
            contentType: ContentType.loginRegister,
            key: snapshot.data.isEmpty ? "null" : snapshot.data,
          ),
        );
      },
    );
  }

  Widget _inputEmail() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        LanguageText.inputRegisterEmail,
        _emailTextField(),
        _lineByEmail(),
      ],
    );
  }

  Widget _emailTextField() {
    return Container(
      width: SFunCommon.width(500),
      height: SFunCommon.height(52),
      child: TextField(
        keyboardType: TextInputType.emailAddress,
        controller: _emailInputController,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 31,
        ),
        cursorColor: AppColor.MAIN_INPUT_COLOR,
        decoration: _inputDecoration(),
        onChanged: (String value) {
          if (value.length > 0) {
            _hiddenTextFileLineByEmail.sink.add(true);
            _disableShowController.sink.add(value);
          } else {
            _hiddenTextFileLineByEmail.sink.add(false);
          }
        },
      ),
    );
  }

  Widget _inputPassword() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        LanguageText.inputRegisterPassword,
        _passwordField(),
        _lineByPassword(),
      ],
    );
  }

  Widget _passwordField() {
    return Container(
      width: SFunCommon.width(500),
      height: SFunCommon.height(52),
      child: TextField(
        controller: _passwordInputController,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 30,
        ),
        obscureText: true,
        cursorColor: AppColor.MAIN_INPUT_COLOR,
        decoration: _inputDecoration(),
        onChanged: (String value) {
          if (value.length > 0) {
            _hiddenTextFileLineByPassword.sink.add(true);
          } else {
            _hiddenTextFileLineByPassword.sink.add(false);
          }
        },
      ),
    );
  }

  Widget _inputSecondPassword() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        LanguageText.inputRegisterPasswordSecond,
        _secondPasswordField(),
        _lineBySecondPassword(),
      ],
    );
  }

  Widget _secondPasswordField() {
    return Container(
      width: SFunCommon.width(500),
      height: SFunCommon.height(52),
      child: TextField(
        controller: _secondPasswordInputController,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 30,
        ),
        obscureText: true,
        cursorColor: AppColor.MAIN_INPUT_COLOR,
        decoration: _inputDecoration(),
        onChanged: (String value) {
          if (value.length > 0) {
            _hiddenTextFileLineBySecondPassword.sink.add(true);
            _disableShowController.sink.add(value);
          } else {
            _hiddenTextFileLineBySecondPassword.sink.add(false);
          }
        },
      ),
    );
  }

  // 注册按钮
  Widget _registerButton() {
    Widget _streamRegisterButton = StreamBuilder(
      stream: _disableShowController.stream,
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        return RaisedButton(
          color: AppColor.MAIN_COLOR_CYAN,
          disabledColor: AppColor.MAIN_COLOR_CYAN_DISABLE,
//          onPressed: _check() ? () {} : null,
          onPressed: _register,
          child: LanguageText.registerText,
          textColor: AppColor.MAIN_COLOR_BLUE,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(SFunCommon.width(20))),
        );
      },
    );

    Widget _button = Container(
      margin: EdgeInsets.only(
        top: SFunCommon.height(330),
      ),
      width: SFunCommon.width(569),
      height: SFunCommon.height(75),
      child: _streamRegisterButton,
    );

    return Container(
      alignment: Alignment.center,
      child: _button,
    );
  }

  void _register() async {
    Map<String, List<Map<String, dynamic>>> rules = {
      "email": [
        {
          ValidateInput.REQUIRE: true,
          ValidateInput.MESSAGE: "emailMust",
        },
        {
          ValidateInput.PATTERN: Pattern.emailPattern,
          ValidateInput.MESSAGE: "emailFormatError"
        },
      ],
      "password": [
        {
          ValidateInput.REQUIRE: true,
          ValidateInput.MESSAGE: "password",
        },
        {
          ValidateInput.EQUAL: _secondPasswordInputController.text,
          ValidateInput.MESSAGE: "inputRegisterPasswordError"
        },
      ],
    };
    Map<String, dynamic> params = {
      "email": _emailInputController.text,
      "password": _passwordInputController.text,
    };
    var validate = ValidateInput(rules: rules, params: params);
    String message = validate.message;
    if(message.isNotEmpty) {
      Show.warnByProvider(contentType: ContentType.loginRegister, key: message);
    } else {

    }
  }

  bool _check() {
    Map<String, List<Map<String, dynamic>>> rules = {
      "email": [
        {
          ValidateInput.REQUIRE: true,
          ValidateInput.MESSAGE: "emailMust",
        },
        {
          ValidateInput.PATTERN: Pattern.emailPattern,
          ValidateInput.MESSAGE: "emailFormatError"
        },
      ],
      "password": [
        {
          ValidateInput.EQUAL: _secondPasswordInputController.text,
          ValidateInput.MESSAGE: "inputRegisterPasswordError"
        },
      ],
    };
    Map<String, dynamic> params = {
      "email": _emailInputController.text,
      "password": _passwordInputController.text,
    };
    var validate = ValidateInput(rules: rules, params: params);
    String message = validate.message;
    _showErrorMessageController.sink.add(message);
    if (message.isEmpty) {
      return true;
    }
    return false;
  }

  // 输入框装饰器
  InputDecoration _inputDecoration() {
    return InputDecoration(
      // 未获得焦点下划线设为灰色
      enabledBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: AppColor.MAIN_COLOR_BLUE),
      ),
      //获得焦点下划线设为蓝色
      focusedBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: AppColor.MAIN_COLOR_BLUE),
      ),
    );
  }

  // 邮箱下划线
  Widget _lineByEmail() {
    return StreamBuilder(
      initialData: false,
      stream: _hiddenTextFileLineByEmail.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return _line(snapshot.data);
      },
    );
  }

  // 密码下划线
  Widget _lineByPassword() {
    return StreamBuilder(
      initialData: false,
      stream: _hiddenTextFileLineByPassword.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return _line(snapshot.data);
      },
    );
  }

  // 再次输入密码下划线
  Widget _lineBySecondPassword() {
    return StreamBuilder(
      initialData: false,
      stream: _hiddenTextFileLineBySecondPassword.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return _line(snapshot.data);
      },
    );
  }

  // 一条虚线
  Widget _line(bool data) {
    return Container(
      margin: EdgeInsets.only(
        bottom: SFunCommon.height(40),
      ),
      child: Offstage(
        offstage: data,
        child: FDottedLine(
          color: Colors.white,
          width: SFunCommon.width(336),
          strokeWidth: 2.0,
          dottedLength: 10.0,
          space: 2.0,
        ),
      ),
    );
  }
}
